/**
 * Created by shenhai on 15/9/25.
 */

var async = require('async');
var moment = require('moment');
var fs = require('fs');
var Community = mongoose.model('community');
var User = mongoose.model('user');
var Topic = mongoose.model('system_specialTopics');
var Share = mongoose.model('mobile_app_share_content');

var pathM = require('path');

exports.topicListService = function(req ,callback) {

    var body = req.body;
    var page = req.params.page;
    var size = Number(req.params.size);
    var index = (Number(req.params.page) - 1) * size;
    var totalPage = 0;

    var option = {};
    var sortType = {dateCreated:-1};
    if (req.body.desc) option.title = new RegExp(req.body.desc);
    //option.isValid = true;

    async.series([
        function (callbackInner) {
            Topic.count(option, function (err, count) {

                totalPage = Math.ceil(count/size);
                var temp = {count: count, totalPage:totalPage};
                callbackInner(err, temp);

            });
        },
        function (callbackInner) {
            Topic.find(option).sort(sortType).skip(index).limit(size).exec(function(err, result) {

                if (result) {

                    async.eachSeries(result, function (topic, callbackInner2) {

                        redisClient.HGET('topicIdPool',topic._id, function (err, res){

                            if(!topic.url){
                                topic.url = TopicsHost + '/' + topic._id + '.html'+ '?topicId=' + topic._id;
                            }
                            //logger.debug(topic._doc.url);
                            callbackInner2(err, topic);
                        });

                    }, function (err) {
                        callbackInner(err, result);
                    })

                };

            });
        }
    ], callback);

};

exports.topicAddService = function(req ,callback) {

    var body = req.body;
    var player = body.desc.match("66player") ? true:false;

    var temp = new Topic();
    temp.title = body.title;
    temp.imageURL = body.imageURL;
    temp.desc = body.desc;
    temp.summary = body.summary;
    temp.shareDesc = body.shareDesc;

    temp.video = [];
    var reg=/<embed.+?src=('|")?([^'"]+)('|")?(?:\s+|>)/gim;
    while(tem=reg.exec(body.desc)){
        logger.debug(tem);
        temp.video.push(tem[2].replace(/http:\/\//,''));
    }

    //获取自增ID
    redisClient.INCR('topicId', function (err, res) {

        var topKey = "topicIdPool";
        var args = [
            topKey,
            res,
            temp._id
        ];
        logger.debug(args);
        var id = res;
        //设置key value
        redisClient.HSET(args, function (err, res) {

            //redisClient.HGET(topKey,result._id, function (err, res) {
            //    logger.debug(res);
            //});
            temp.url = TopicsHost + '/' + id + '.html'+ '?topicId=' + id;

            temp.save(function(err, result) {
                if (!err) {
                    temp.topicId = id;
                    temp.id = temp._id;
                    exports.generateTopicHtmlService(temp, player);

                };

                var share = new Share();
                share.key = temp._id;
                share.title = body.title;
                share.desc = body.shareDesc;
                share.image = body.imageURL;
                share.url =  temp.url;

                share.save(function(err, result) {

                    callback(err, result);
                });

            });


        });


    });


};

exports.topicEditService = function(req ,callback) {

    var body = req.body;

    var player = body.desc.match("embed") ? true:false;

    var data = {};
    if (body.title) data.title = body.title;
    if (body.imageURL) data.imageURL = body.imageURL;
    if (body.desc) data.desc = body.desc;
    if (body.summary) data.summary = body.summary;
    if (body.shareDesc) data.shareDesc = body.shareDesc;

    data.video = [];
    var reg=/<embed.+?src=('|")?([^'"]+)('|")?(?:\s+|>)/gim;
    while(tem=reg.exec(body.desc)){
        logger.debug(tem);
        data.video.push(tem[2].replace(/http:\/\//,''));
    }
    body.video = data.video;
    logger.debug(body);
    Topic.update({_id: body.id}, data, function(err) {
        if(!body.topicId) {
            //新数据使用自增id生成html
            //旧数据依然使用id生成html
            body.topicId = body.id;
        }
        if (!err) exports.generateTopicHtmlService(body, player);

        var data2 = {};
        if (body.title) data2.title = body.title;
        if (body.imageURL) data2.image = body.imageURL;
        if (body.shareDesc) data2.desc = body.shareDesc;

        Share.update({key: body.id}, data2, function(err) {
            callback(err);
        });

        //
        //redisClient.HGET('topicIdPool', body.topicId, function (err, res) {
        //    logger.debug(res);
        //    body.topid = res;
        //    if (!err) exports.generateTopicHtmlService(body, player);
        //    callback(err);
        //});

    });

};

exports.generateTopicHtmlService = function (data, player) {

    var path = topicPath;

    var hasVideo = player && data.video && data.video.length;
    var id = data.topicId;

    logger.debug('id:');
    logger.debug(id);

    var str = fs.readFileSync(pathM.join(__dirname, "../../../../public/pages/static/mobile/js/topic/" + (hasVideo ? 'template-player.html':'template.html')), 'utf-8');
    // var str = fs.readFileSync("public/pages/static/mobile/js/topic/" + (hasVideo ? 'template-player.html':'template.html'), 'utf-8');
    var str = fs.readFileSync(pathM.join(__dirname, "../../../../public/pages/static/mobile/js/topic/" + (hasVideo ? 'template-player.html':'template.html')), 'utf-8');
    if (hasVideo) str = str.replace(/youku_player_vid/g, data.video[0]);

    str =  str.replace('setShareContent("community_week_report")','setShareContent("'+ data.id +'")');

    logger.debug(hasVideo ? 'yes':'no');

    var array = str.split('{{}}');
    var date = (data.dateCreated ? moment(data.dateCreated):moment()).format('YYYY-MM-DD HH:mm');

    var header = '<B><font  size="5">' + data.title + '</font></B><br>' + date + '<br>';

    var desc = data.desc.replace(/<embed(.*?>)/gi, '<div id="youkuplayer" style="width:100%;height:300px"></div>');
    /*  宝宝树66小区二次改造    mod   chenf  20170816  start   */
    var img = '<div><img src="'+data._doc.imageURL+'" style="width:100%;"></div>'
    /*fs.writeFile(path + "/" + id + ".html", array[0] + header + desc + array[1], function (err) {*/
    fs.writeFile(path + "/" + id + ".html", array[0] + header + desc + img + array[1], function (err) {
    /*  宝宝树66小区二次改造    mod   chenf  20170816  end   */
    });

    //logger.debug(str);
    //var desc = data.desc.replace(/<embed(.*?>)/gi, function (a, b) {
    //    return  '<div id="' + 'youkuplayer' + data.video[b] + '" style="width:480px;height:400px"></div>';
    //});
};

exports.remove = function (id) {

    var fullpath = resTopicPath();

    fs.unlink(fullpath + "/" + id + ".html", function (err) {
        console.log(err)
    });
}

exports.topicStatusService = function(req ,callback) {

    if (!req.body.id) return callback('id错误', null);

    Topic.update({_id:req.body.id}, {isValid:req.body.isValid}, callback);
};

exports.topicDeleteService = function(req ,callback) {

    var id = req.body.id;

    if (!id) return callback('id错误', null);


    Topic.remove({_id:id}, callback);
    exports.remove(id);
};